<template>
    <!--
        新增或编辑表单
    -->
    <el-dialog 
        :title="title" 
        :visible.sync="visible"
        v-if="visible"
        width="600px"
        :show-close="false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        append-to-body>
        <el-form  ref="FORM" :model="form" :rules="rule" label-width="120px">
            <el-row>
                <el-col :span="24">
                    <el-form-item label="标签键" prop="mkey">
                        <el-input v-model="form.mkey" placeholder="请输入标签键" style="width: 100%" :readonly="readonly"/>
                    </el-form-item>
                </el-col>
            </el-row>
            <el-row>
                <el-col :span="24">
                    <el-form-item label="标签值" prop="mvalue">
                        <el-input v-model="form.mvalue" placeholder="请输入标签值" style="width: 100%"/>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submit()">确 定</el-button>
            <el-button @click="close()">关 闭</el-button>
        </div>
    </el-dialog>
</template>

<script>

export default {
    data() {
        return {
            title: '',
            visible: false,
            form: {
                mkey: null,
                mvalue: null
            },
            rule: {
                mkey: [{ required: true, message: '标签键不能为空', trigger: 'blur' }],
                mvalue: [{ required: true, message: '标签值不能为空', trigger: 'blur' }],
            },
            loading: false,
            readonly: false
        }
    },
    methods: {
        /**
         * 提交表单
         */
        async submit() {
            if (!this.valid('FORM')) return
            const row = Object.assign(this.form, {});           
            this.$emit('success', JSON.stringify(row))
            this.$message.success('操作成功')
            this.close()
        },

        /**
         * 校验表单
         */
        valid(formRef) {
            let res = false;
            this.$refs[formRef].validate((valid) => {
                if (valid) {
                    res = valid
                }
            })
            return res;
        },

        /**
         * 打开表单
         */
        open(row) {
            this.visible = true
            if (row.mkey) {
                this.title = '编辑元数据'
                this.readonly = true    
            } else {
                this.title = '新增元数据'
                this.readonly = false
            }
            // 赋值
            this.form = Object.assign({}, row)
        },

        /**
         * 关闭表单
         */
        close() {
            this.$refs['FORM'].resetFields()
            this.$refs['FORM'].clearValidate()
            this.visible = false
        }
    }
}
</script>

<style>

</style>